<?php
/**
 * 客户基本信息上传
 */
namespace app\adminweb\controller;
use app\common\model\Record;
use think\Controller;
use \think\Validate;
header("Access-Control-Allow-Origin: * ");
header("Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE");
class Message  extends Pre
{
    //添加当前客户信息
    public function inserts(){
        $userInfo = $this -> loginInfo;
        $account = new \app\common\model\Message();
        return $account -> inserts($userInfo);
    }
    //删除当前客户信息
    public function dels(){
        $account = new \app\common\model\Message();
        return $account -> dels();
    }
    //客户管理筛选
    public function search(){
        $data = input('param.');
        $userInfo = $this -> loginInfo;
        if($userInfo['role'] == 20){
            $num = \app\common\model\Account::where('distribute',$userInfo['id'])
                -> column('id');
            $allAccount = $num;
            $findRecord[] = ['a_id','in',$num];
            while (!empty($b_id = \app\common\model\Record::where($findRecord)->column('b_id'))){
                $findRecord = [];
                $allAccount = array_merge($allAccount,$b_id);
                $findRecord[] = ['a_id','in',$b_id];
            }
        }else{
            $allAccount[] = $userInfo['id'];
            $findRecord[] = ['a_id','eq',$userInfo['id']];
            while (!empty($b_id = \app\common\model\Record::where($findRecord)->column('b_id'))){
                $findRecord = [];
                $allAccount = array_merge($allAccount,$b_id);
                $findRecord[] = ['a_id','in',$b_id];
            }
        }
        if($data['key']){
            $map[] = ['account_id','in',$allAccount];
            $data['key'] = trim($data['key']);
            $mapx[] = ['name|telephone|notes','like',"%$data[key]%"];
            $add1 = \app\common\model\Message::withTrashed() ->where($mapx) -> column('id');
            $mapping[] = ['content','like',"%$data[key]%"];
            $numb = \app\common\model\Follow::withTrashed() ->where($mapping) -> column('message_id');
            if($numb){
                $add2 = array_filter(array_merge($add1,$numb));
                $map[] = ['id','in',$add2];
            }else{
                $map[] = ['id','in',$add1];
            }
            $data['page'] = 1;
        }
        if($data['type'] && !$data['simple']){
            for($i=0;$i<count($data['type']);$i++){
                switch ($data['type'][$i]['name']){
                    case 'type':if($data['type'][$i]['value']){
                        $map[] = ['account_id','in',$allAccount];
                        switch ($data['type'][$i]['value']){
                            case '跟进中':$map[] = ['status','eq','跟进中'];break;
                            case '星标':$map[] = ['status','eq','星标'];break;
                            case '失效':$map[] = ['status','eq','失效'];break;
                            case '已定':$map[] = ['status','eq','已定'];break;
                            case '已买':$map[] = ['status','eq','已买'];break;default;
                        }
                    };break;
                    case 'date':if($data['type'][$i]['value']){
                        $map[] = ['account_id','in',$allAccount];
                        $str = $data['type'][$i]['value'];
                        $a5 = stripos($str,'-');
                        $start = $this -> msubstr($str,0,$a5-1, $charset="utf-8", $suffix=false);
                        $end = $this -> msubstr($str,$a5+2,$a5, $charset="utf-8", $suffix=false);
                        if(trim($start) && trim($end)){
                            $map[] = ['schedule','between',[strtotime(trim($start)),strtotime(trim($end))]];
                        }else{
                            $map[] = ['schedule','between',0,0];
                        }
                    };break;
                    case 'receive':if($data['type'][$i]['value']){
                        $arr[] = '';
                        $findRe[] = ['a_id','eq',$data['type'][$i]['value']];
                        while (!empty($b_id1 = \app\common\model\Record::where($findRe)
                            ->column('b_id'))){
                            $findRe = [];
                            $arr = array_merge($arr,$b_id1);
                            $findRe[] = ['a_id','in',$b_id1];
                        }
                        $map3[] = ['to_account_id','in',array_filter($arr)];
                        $id3 = \app\common\model\Transfer::where($map3) -> column('message_id');
                        if($id3){
                            $map[] = ['id','in',$id3];
                        }else{
                            $map[] = ['id','in',0];
                        }
                    };break;
                    case 'houses':if($data['type'][$i]['value']){
                        $map[] = ['account_id','in',$allAccount];
                        $map[] = ['building','eq',$data['type'][$i]['value']];
                    };break;
                    case 'source':if($data['type'][$i]['value']){
                        $map[] = ['account_id','in',$allAccount];
                        $arr[] = intval($data['type'][$i]['value']);
                        $findRe[] = ['a_id','eq',$data['type'][$i]['value']];
                        while (!empty($b_id1 = \app\common\model\Record::where($findRe)
                            ->column('b_id'))){
                            $findRe = [];
                            $arr = array_merge($arr,$b_id1);
                            $findRe[] = ['a_id','in',$b_id1];
                        }
                        $map[] = ['account_id','in',$arr];
                    };break;
                    case 'luru':if($data['type'][$i]['value']){
                        $map[] = ['account_id','eq',$data['type'][$i]['value']];
                    };break;
                    case 'jieshou':if($data['type'][$i]['value']){
                        $map3[] = ['to_account_id','eq',$data['type'][$i]['value']];
                        $id3 = \app\common\model\Transfer::where($map3) -> column('message_id');
                        if($id3){
                            $map[] = ['id','in',$id3];
                        }else{
                            $map[] = ['id','in',0];
                        }
                    };break;
                    case 'order' :if($data['type'][$i]['value']){
                        switch ($data['type'][$i]['value']){
                            case 1: $order = 'time ASC';break;
                            case 2: $order = 'time DESC';break;default;
                        }
                    }break;default;
                }
            }
        }
        if($data['simple']) {
            if($data['type']){
                $map[] = ['account_id','in',$allAccount];
                $map[] = ['status','eq',$data['type']];
            }
            if($data['date']){
                $map[] = ['account_id','in',$allAccount];
                $str = $data['date'];
                $a5 = stripos($str,'-');
                $start = $this -> msubstr($str,0,$a5-1, $charset="utf-8", $suffix=false);
                $end = $this -> msubstr($str,$a5+2,$a5, $charset="utf-8", $suffix=false);
                if(trim($start) && trim($end)){
                    $map[] = ['schedule','between',[strtotime(trim($start)),strtotime(trim($end))]];
                }else{
                    $map[] = ['schedule','between',0,0];
                }
            }
            if($data['receive']){
                $arr[] = '';
                $findRe[] = ['a_id','eq',$data['receive']];
                while (!empty($b_id1 = \app\common\model\Record::where($findRe)
                    ->column('b_id'))){
                    $findRe = [];
                    $arr = array_merge($arr,$b_id1);
                    $findRe[] = ['a_id','in',$b_id1];
                }
                $map3[] = ['to_account_id','in',array_filter($arr)];
                $id3 = \app\common\model\Transfer::where($map3) -> column('message_id');
                if($id3){
                    $map[] = ['id','in',$id3];
                }else{
                    $map[] = ['id','in',0];
                }
            }
            if($data['houses']){
                $map[] = ['account_id','in',$allAccount];
                $map[] = ['building','eq',$data['houses']];
            }
            if($data['source']){
                $map[] = ['account_id','in',$allAccount];
                $arr[] = intval($data['source']);
                $findRe[] = ['a_id','eq',$data['source']];
                while (!empty($b_id1 = \app\common\model\Record::where($findRe)
                    ->column('b_id'))){
                    $findRe = [];
                    $arr = array_merge($arr,$b_id1);
                    $findRe[] = ['a_id','in',$b_id1];
                }
                $map[] = ['account_id','in',$arr];
            }
            if($data['luru'])
                $map[] = ['account_id','eq',$data['luru']];
            if($data['jieshou']){
                $map3[] = ['to_account_id','eq',$data['jieshou']];
                $id3 = \app\common\model\Transfer::where($map3) -> column('message_id');
                if($id3){
                    $map[] = ['id','in',$id3];
                }else{
                    $map[] = ['id','in',0];
                }
            }
            if($data['order']){
                switch ($data['order']){
                    case 1: $order = 'time ASC';break;
                    case 2: $order = 'time DESC';break;default;
                }
            }
        }
        if($data['yufang']){
            $map[] = ['account_id','in',$allAccount];
            $map[] =  ['schedule','elt',strtotime(date('Y-m-d',strtotime('+1 day')))];
            $map[] = ['status','eq','跟进中'];
        }
        if($data['visit']){
            $mapwu[] = ['visit','neq',''];
            $mapwu[] = ['account_id','in',$allAccount];
            $resultwu = \app\common\model\Message::where($mapwu) -> column('id');
            $map[] = ['id','in',$resultwu];
        }
        if(!$map)
            $map[] = ['account_id','in',$allAccount];
        if(!isset($order)){
            $order = 'time DESC';
        }
        if($data['id']){
            $sign = \app\common\model\Record::where('a_id',$data['id']) -> column('b_id');
            $number = \app\common\model\Account::where('id','in',$sign)
                        -> field('id,name') -> select();
            $arr1[] = intval($data['id']);
            $find[] = ['a_id','eq',$data['id']];
            while (!empty($b_id2 = \app\common\model\Record::where($find)
                ->column('b_id'))){
                $find = [];
                $arr1 = array_merge($arr1,$b_id2);
                $find[] = ['a_id','in',$b_id2];
            }
            $map[] = ['account_id','in',$arr1];
        }
        $re1 = \app\common\model\Message::withTrashed()->where($map) -> count();
        $ab = $re1/10;
        if(!is_int($aa)){
            $ab = intval($ab)+1;
        }
        if($data['page'] >= $ab){
            $data['page'] = $ab;
        }
        if(!$map[0][2]){
            unset($map);
            $map[] = ['account_id','lt','0'];
        }
        if($data['simple']){
            $result = \app\common\model\Message::withTrashed()->where($map)
                ->with('followInfo,dealInfo,transferInfo,visitInfo')-> order($order)->select();
        }else{
            $result = \app\common\model\Message::withTrashed()->where($map)
                ->with('followInfo,dealInfo,transferInfo,visitInfo')
                -> page($data['page'],$data['limit'])
                -> order($order)->select();
        }
        foreach ($result as $value){
            $wang = \app\common\model\Building::get($value['building']);
            $value['building'] = $wang['name'];
            $value['type'] = $value['house1'].'室'.$value['house2'].'厅'.$value['house3'].'卫'.$value['house4'].'厨';
            //隐藏联系方式中间4位
            if(!in_array($userInfo['id'],array(1,3,9))){
                $value['telephone']=  $this->hidtel($value['telephone']);
            }
            $value['schedule'] = date("Y-m-d H:i:s", $value['schedule']);
            $value['time'] = date("Y-m-d H:i:s", $value['time']);
            if($userInfo['role'] == 20){
                $b_id1 = $num = \app\common\model\Account::where('distribute',$userInfo['id'])
                    -> column('id');
            }else{
                $b_id1 = \app\common\model\Record::where('a_id',$userInfo['id'])
                    ->column('b_id');
            }
            $findRecord1[] = ['b_id','eq',$value['account_id']];
            $nu = \app\common\model\Record::where($findRecord1) -> select();
            if(count($nu) !== 0){
                while ($b_id2 = \app\common\model\Record::where($findRecord1)
                    ->column('a_id')){
                    if(in_array($b_id2[0],$b_id1)){
                        $aa = $b_id2[0];break;
                    }else{
                        $aa = $value['account_id'];
                    }
                    $findRecord1 = [];
                    $findRecord1[] = ['b_id','eq',$b_id2[0]];
                }
                $findRecord1 = [];
            }
            if(!isset($aa)){
                $aa = $value['account_id'];
            }
            $fuze = \app\common\model\Account::get($aa);
            $wang = \app\common\model\Account::get($value['account_id']);
            $value['account_id1'] = $wang['name'];
            $wangcount = count($value['follow_info']);
            if($wangcount !== 0){
                $date = $value['follow_info'][0]['date'];
                foreach ($value['follow_info'] as $k => $va){
                    $da = \app\common\model\Account::withTrashed() -> with('roleInfo')
                        -> where('id',$va['account_id']) -> find();
                    if($da)
                        $da -> toArray();
                    $value['follow_info'][$k]['id'] = $va['id'];
                    $value['follow_info'][$k]['content'] = $va['content'];
                    $value['follow_info'][$k]['message_id'] = $va['message_id'];
                    $value['follow_info'][$k]['wang'] = $da['name'];
                    $value['follow_info'][$k]['role'] = $da['role_info']['rolename'];
                    $value['follow_info'][$k]['date'] = date('Y-m-d H:i:s',$va['date']);
                    $content = $content.'/'.$va['content'];
                }
            }
            $value['content'] = ltrim($content,'/');
            if($fuze){
                $value['account_id'] = $fuze['name'];
            }else{
                $value['account_id'] = $wang['name'];
            }
            if($date){
                $value['date'] = date('Y-m-d H:i:s',$date);
            }else{
                $value['date'] = '暂无';
            }
            if($value['deal_info']){
                $value['deal_info']->toArray();
                foreach ($value['deal_info'] as $valu){
                    $valu['img'] = 'https://show.enterlo.com'.$valu['img'];
                }
            }
            if($value['visit']){
                $value['visit'] = 'https://show.enterlo.com'.$value['visit'];
            }
            if($value['visit_info']){
                foreach ($value['visit_info'] as $key => $v){
                        $value['visit_info'][$key]['content'] =
                                'https://show.enterlo.com'.$value['visit_info'][$key]['content'];
                }
            }
            if($value['transfer_info']){
                $name = \app\common\model\Account::with('roleInfo')
                    -> where('id',$value['transfer_info']['to_account_id'])
                    -> find();
                $value['transfer_info']['to_account_id'] = $name['name'];
                $value['transfer_info']['role'] = $name['role_info']['rolename'];
                $value['transfer_info']['date'] =
                    date('Y-m-d H:i:s',$value['transfer_info']['date']);
            }
            unset($aa);
            unset($date);
            unset($content);
        }
        $count = \app\common\model\Message::withTrashed()->where($map)->count();
        $array = array('code'=>0,'msg' =>'','count'=>$count,'data'=>$result,'number'=>$number,);
        if($data['simple']){
            $xlsName  = "客户信息表";
            $xlsCell  = array(
                array('name','客户姓名'),
                array('telephone','客户电话'),
                array('account_id','录入人姓名'),
                array('account_id1','跟进人姓名'),
                array('sex','性别'),
                array('building','意向楼盘'),
                array('type','意向户型'),
                array('schedule','约访时间'),
                array('time','录入时间'),
                array('price','成交金额'),
                array('price_end','最终成交金额'),
                array('content','跟进信息'),
                array('status','跟进状态'),
                array('notes','备注'),
            );
            $this->exportExcel($xlsName,$xlsCell,$result);
        }else{
            return $array;
        }
    }
    //改变当前跟进状态
    public function follow(){
        $data = input('param.');
        $userInfo = $this -> loginInfo;
        $map[] = ['id','eq',$data['id']];
        $result = \app\common\model\Message::withTrashed()->where($map) -> find();
        if($result['delete_time']){
            $array = array('code'=>0,'msg' =>'当前客户已删除');
        }else{
            if(in_array($userInfo['id'],array(3,9))){
                \app\common\model\Message::where($map)-> setField('status',$data['status']);
                /*\app\common\model\Message::where($map)-> setField('time',time());*/
                $array = array('code'=>0,'msg' =>'更新成功');
            }else{
                $array = array('code'=>0,'msg' =>'没有权限更改');
            }
        }
        return $array;
    }
    //意向楼盘
    public function building(){
        //楼盘名
        $loginInfo = $this -> loginInfo;
        $building = \app\common\model\Building::column('company');
        foreach ($building as $va){
            if(!in_array($va,$tmp)){
                $tmp[] = $va;
            }
        }
        foreach ($tmp as $va){
            $map5[] = ['company','eq',$va];
            $project = \app\common\model\Building::where($map5)
                -> field('id,name') -> select() -> toArray();
            $tmp2[] = $project;
            unset($map5);
        }
        foreach ($tmp2 as $val){
            foreach ($val as $valu){
                $wang[] = $valu;
            }
        }
        foreach ($wang as $value){
            $na = array('project' => $value['name']);
            $project1 = array_merge($value,$na);
            $tmp1[] = $project1;
        }
        //负责人
        $userInfo = $this -> loginInfo;
        $allAccount[] = $userInfo['id'];
        $findRecord[] = ['a_id','eq',$userInfo['id']];
        $b_id = \app\common\model\Record::where($findRecord)->column('b_id');
        foreach ($b_id as $value){
            $resultdata = \app\common\model\Account::field('id,name')
                            -> where('id','eq',$value) -> find();
            if($resultdata){
                $datainfo[] = $resultdata -> toArray();
            }else{
                $datainfo = array();
            }
        }
        //我的所有下级用户
        $allAccount1[] = $userInfo['id'];
        $findRecord1[] = ['a_id','eq',$userInfo['id']];
        while (!empty($b_id1 = \app\common\model\Record::where($findRecord1)->column('b_id'))){
            $findRecord1 = [];
            $allAccount1 = array_merge($allAccount1,$b_id1);
            $findRecord1[] = ['a_id','in',$b_id1];
        }
        $mapping[] = ['id','in',$allAccount1];
        $va = \app\common\model\Account::where($mapping) -> field('id,name,role') -> select();
        if($va){
            $va ->toArray();
            foreach ($va as $ve){
                if(!in_array($ve['role'],array(1,2,21,30,3,10,20,4,5,6,11,12,13,14,15,17,18))){
                        $vue[] = $ve;
                }}
        }else{
            $vue = array();
        }
        return json([
            'building' => $tmp1,
            'datainfo' => $datainfo,
            'luru' => $vue
        ]);
    }
    //截取字符串
    function msubstr($str, $start=0, $length, $charset="utf-8", $suffix=true){
        if(function_exists("mb_substr")){
            $slice= mb_substr($str, $start, $length, $charset);
        }elseif(function_exists('iconv_substr')) {
            $slice= iconv_substr($str,$start,$length,$charset);
        }else{
            $re['utf-8'] = "/[x01-x7f]|[xc2-xdf][x80-xbf]|[xe0-xef][x80-xbf]{2}|[xf0-xff][x80-xbf]{3}/";
            $re['gb2312'] = "/[x01-x7f]|[xb0-xf7][xa0-xfe]/";
            $re['gbk'] = "/[x01-x7f]|[x81-xfe][x40-xfe]/";
            $re['big5'] = "/[x01-x7f]|[x81-xfe]([x40-x7e]|xa1-xfe])/";
            preg_match_all($re[$charset], $str, $match);
            $slice = join("",array_slice($match[0], $start, $length));
        }
        $fix='';
        if(strlen($slice) < strlen($str)){
            $fix='...';
        }
        return $suffix ? $slice.$fix : $slice;
    }
    //隐藏电话号码
    function hidtel($phone){
        //隐藏邮箱
        if(strpos($phone, '@')) {
            $email_array = explode("@", $phone);
            $prevfix = (strlen($email_array[0]) < 4) ? "" : substr($phone, 0, 3); //邮箱前缀
            $count = 0;
            $str = preg_replace('/([\d\w+_-]{0,100})@/', '***@', $phone, -1, $count);
            $rs = $prevfix . $str;
            return $rs;
        } else {
            //隐藏联系方式中间4位
            $Istelephone = preg_match('/(0[0-9]{2,3}[\-]?[2-9][0-9]{6,7}[\-]?[0-9]?)/i', $phone);           //固定电话
            if($Istelephone) {
                return preg_replace('/(0[0-9]{2,3}[\-]?[2-9])[0-9]{3,4}([0-9]{3}[\-]?[0-9]?)/i', '$1****$2', $phone);
            } else {
                return preg_replace('/(1[0-9]{1}[0-9])[0-9]{4}([0-9]{4})/i', '$1****$2', $phone);
            }
        }
    }
    //导出表格
    public function exportExcel($expTitle,$expCellName,$expTableData)
    {
        $xlsTitle = iconv('utf-8', 'gb2312', $expTitle);//文件名称
        $fileName = $xlsTitle . date('_YmdHis');//or $xlsTitle 文件名称可根据自己情况设定
        $cellNum = count($expCellName);
        $dataNum = count($expTableData);
        // 引入核心文件
        require '../extend/PHPExcel/PHPExcel.php';
        $objPHPExcel = new \PHPExcel();
        $cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ');
        $objPHPExcel->getActiveSheet(0)->mergeCells('A1:' . $cellName[$cellNum - 1] . '1');//合并单元格
         $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', $expTitle.'  表格导出时间:'.date('Y-m-d H:i:s'));
        for ($i = 0; $i < $cellNum; $i++){
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellName[$i] . '2', $expCellName[$i][1]);
        }
        // Miscellaneous glyphs, UTF-8
        for ($i = 0; $i < $dataNum; $i++) {
            for ($j = 0; $j < $cellNum; $j++) {
                $objPHPExcel->getActiveSheet(0)->setCellValue($cellName[$j] . ($i + 3), $expTableData[$i][$expCellName[$j][0]]);
            }
        }
        $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(13);
        $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(15);
        $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(15);
        $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(15);
        $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(22);
        $objPHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(22);
        $objPHPExcel->getActiveSheet()->getColumnDimension('J')->setWidth(13);
        $objPHPExcel->getActiveSheet()->getColumnDimension('K')->setWidth(13);
        $objPHPExcel->getActiveSheet()->getColumnDimension('L')->setWidth(50);
        $objPHPExcel->getActiveSheet()->getColumnDimension('M')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('N')->setAutoSize(true);
        $objPHPExcel->getActiveSheet()->getColumnDimension('0')->setAutoSize(true);
        header('pragma:public');
        header('Content-type:application/vnd.ms-excel;charset=utf-8;name="' . $xlsTitle . '.xls"');
        header("Content-Disposition:attachment;filename=$fileName.xls");//attachment新窗口打印inline本窗口打印
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;
    }
    //导入表格
    public function upload(){
        //获取表单上传文件
        $file = request()->file('excel');
        if($file){
            $file_types = explode(".", $_FILES ['myfile'] ['name']);
            $file_type = $file_types [count($file_types) - 1];//xls后缀
            /*判别是不是.xls文件，判别是不是excel文件*/
            $info = $file->move('upload/excle');
            $file_path = '/public/upload/excle/'.$info->getSaveName(); //上传后的EXCEL路径
            switch ($extension) {
                case 'xls':
                    $type = 'Excel5';
                    break;
                case 'xlsx':
                    $type = 'Excel2007';
                    break;
            }
            return $file_path;
        }
    }
}